package blbetter.db.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

public class HttpPostSender {
	public static ArrayList<String> sendPost(String urlStr,
			Map<String, String> dataMap) {
		ArrayList<String> resp = new ArrayList<String>();
		try {
			// Construct data
			String data = "";
			int di = 0;
			for (String key : dataMap.keySet()) {
				if (di == 0) {
					data += URLEncoder.encode(key, "UTF-8") + "="
							+ URLEncoder.encode(dataMap.get(key), "UTF-8");
				} else {
					data += "&" + URLEncoder.encode(key, "UTF-8") + "="
							+ URLEncoder.encode(dataMap.get(key), "UTF-8");
					di++;
				}
			}

			// Send data
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn
					.getOutputStream());
			wr.write(data);
			wr.flush();

			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn
					.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				resp.add(line);
			}
			wr.close();
			rd.close();

		} catch (Exception e) {
			System.err.println("HttpPostSender.sendPost(): exception");
			e.printStackTrace();
		}

		return resp;
	}
}
